<template>
  <div class="select-time-container">
    <u-select
      class="u-select"
      v-model="value"
      :list="timePeriod"
      :mask-close-able="false"
      confirm-color="#f4756b"
      @cancel="handleCancel"
      @confirm="handleConfirm" />
  </div>
</template>

<script setup lang="ts">
  interface SelectTimeProps {
    modelValue: boolean //是否显示Popup弹窗
    showCloseBtn?: boolean //是否显示关闭按钮，默认显示
    timeLimit?: string //可选的时间段，格式如："9:00-21:00"
    timeInterval?: number //时间段间隔，默认为30
  }

  const props = withDefaults(defineProps<SelectTimeProps>(), {
    modelValue: false,
    showCloseBtn: true,
    timeLimit: '',
    timeInterval: 30
  })

  const emit = defineEmits(['confirm', 'cancel'])

  const startHour = ref<number>(NaN) //开始小时
  const startMinute = ref<number>(NaN) //开始分钟
  const endHour = ref<number>(NaN) //结束小时
  const endMinute = ref<number>(NaN) //结束分钟
  const timePeriod = ref<Array<any>>([])  //格式化后的时间段数组

  // 初始化
  const init = (): void => {
    const timeSplit = props.timeLimit.split('-')
    if (timeSplit.length === 2 && timeSplit[0] !== '' && timeSplit[1] !== '') {
      const startTime = timeSplit[0].replaceAll(' ', '')
      const endTime = timeSplit[1].replaceAll(' ', '')
      const startTimeSplit = startTime.split(':')
      const endTimeSplit = endTime.split(':')
      if (startTimeSplit.length === 2
        && endTimeSplit.length === 2
        && startTimeSplit[0] !== ''
        && endTimeSplit[0] !== ''
        && startTimeSplit[1] !== ''
        && endTimeSplit[1] !== '') {
        if (!isNaN(startHour.value = parseInt(startTimeSplit[0]))
          && !isNaN(startMinute.value = parseInt(startTimeSplit[1]))
          && !isNaN(endHour.value = parseInt(endTimeSplit[0]))
          && !isNaN(endMinute.value = parseInt(endTimeSplit[1]))
          && startHour.value <= 23
          && startHour.value >= 0
          && endHour.value <= 24
          && endHour.value >= 0
          && startMinute.value >= 0
          && startMinute.value <= 59
          && endMinute.value >= 0
          && endMinute.value <= 59
        ) {
          //timeLimit属性值通过验证
          computeTimePeriod()
          return
        }
      }
    }
    //timeLimit属性值不合法
    console.error(`Illegal variable "timeLimit: ${props.timeLimit}"`)
  }

  // 计算时间段，并添加到picker中
  const computeTimePeriod = () => {
    const hourPeriod = endHour.value - startHour.value //开始时间与结束时间的小时时间差
    let periodAmount = hourPeriod * 60 / props.timeInterval //切分时间段的数量
    if (startMinute.value !== 0) {
      periodAmount -= Math.floor(startMinute.value / props.timeInterval)
    }
    if (endMinute.value !== 0) {
      if (endMinute.value % props.timeInterval === 0) {
        periodAmount -= 1
      }
      periodAmount += Math.floor(endMinute.value / props.timeInterval) + 1
    }
    let index = 0
    let startHourTemp = startHour.value
    let startMinuteTemp = startMinute.value
    let endHourTemp = startHourTemp
    let endMinuteTemp = startMinuteTemp
    while (index < periodAmount) {
      if (endMinuteTemp + props.timeInterval >= 60) {
        endHourTemp += 1
        endMinuteTemp = 0
      } else {
        endMinuteTemp += props.timeInterval
      }
      timePeriod.value.push({
        value: index,
        label: `${startHourTemp.toString().padStart(2, '0')}:${startMinuteTemp === 0 ? '00' : startMinuteTemp.toString().padStart(2, '0')} - ${endHourTemp.toString().padStart(2, '0')}:${endMinuteTemp === 0 ? '00' : endMinuteTemp.toString().padStart(2, '0')}`
      })
      startHourTemp = endHourTemp
      startMinuteTemp = endMinuteTemp
      index += 1
    }
  }

  // popup打开事件
  const handleCancel = () => {
    emit('cancel')
  }

  // popup关闭事件
  const handleConfirm = (e: any) => {
    console.log(e)
    emit('confirm', e)
  }

  //强制触发props变化监听器
  const propsChange = computed(() => `${props.timeInterval}${props.timeLimit}`)
  watch(
    () => propsChange.value,
    () => init()
  )

  const value = ref(false)
  watch(
    () => props.modelValue,
    (nval) => value.value = nval
  )
</script>